package com.yun.algorithmproblem.leetcode;

public class Leetcode641 {
    static class MyCircularDeque {

        static class Node {
            Node prev;
            Node next;
            int value;

            public Node() {
            }

            public Node(int value) {
                this.value = value;
            }

            public Node(Node prev, Node next, int value) {
                this.prev = prev;
                this.next = next;
                this.value = value;
            }
        }

        Node head;
        Node tail;
        int capacity;

        int size;

        public MyCircularDeque(int k) {
            head = new Node();
            tail = new Node();
            head.next = tail;
            tail.prev = head;
            capacity = k;
            size = 0;
        }

        public boolean insertFront(int value) {
            if(isFull()){
                return false;
            }
            Node node=new Node(value);
            Node oldFirst=head.next;
            head.next=node;
            node.prev=head;
            node.next=oldFirst;
            oldFirst.prev=node;
            size++;
            return true;
        }

        public boolean insertLast(int value) {
            if(isFull()){
                return false;
            }
            Node node=new Node(value);
            Node oldLast=tail.prev;
            tail.prev=node;
            node.next=tail;
            node.prev=oldLast;
            oldLast.next=node;
            size++;
            return true;
        }

        public boolean deleteFront() {
            if (isEmpty()) {
                return false;
            }
            Node deleted = head.next;
            Node newFirst = deleted.next;
            head.next = newFirst;
            newFirst.prev = head;
            deleted.prev = null;
            deleted.next = null;
            size--;
            return true;
        }

        public boolean deleteLast() {
            if (isEmpty()) {
                return false;
            }
            Node deleted = tail.prev;
            Node newLast = deleted.prev;
            tail.prev = newLast;
            newLast.next = tail;
            deleted.prev = null;
            deleted.next = null;
            size--;
            return true;
        }

        public int getFront() {
            if (isEmpty()) {
                return -1;
            }
            return head.next.value;
        }

        public int getRear() {
            if (isEmpty()) {
                return -1;
            }
            return tail.prev.value;
        }

        public boolean isEmpty() {
            return size == 0;
        }

        public boolean isFull() {
            return size == capacity;
        }
    }
}
